<template>
    <div class="bg">
        <!-- <div>视频生成中...</div> -->

        <!-- <van-button type="primary" @click="toPreviewPage">预览页面</van-button> -->
        <div>
            <div class="box">
                <div class="Loading" v-if="processCode==='111111' ">
                    <van-loading />
                    <p>图片审核中，请稍等...</p>
                </div>
                <div class="content" v-else-if="processCode==='000000' ">
                    <van-circle
                        :current-rate="currentRate"
                        :rate="currentRate"
                        :speed="50"
                        :text="text"
                        size="80px"
                        stroke-width="100"
                        layer-color="#333"                        
                        color="white"
                    />
                    <p>视频生成中</p>
                    <!-- <button @click="increaseProgress">addProcess</button> -->
                </div>
            </div>
            <p class="text">
                离开页面后，您可随时在<br>[AI3D视频彩铃首页-创作记录]查看生成结果
            </p>
        </div>
        <!-- <van-button type="primary" @click="toGetImgUrl">获取url</van-button> -->
        <van-button @click="toGetImgUrl" class="publishBtn">发布视频</van-button>
    </div>
</template>

<script lang="ts" setup name="produceVideoPage">
import { onMounted, reactive, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { apiUploadFile,apiGetImgUrl,apiGetImgVideo,apiGetProcess } from "../../utils/api";
import { useNoloStore } from "../../store";
import { ROUTER_NAME_PREVIEW_PAGE } from "../../route";
import { ROUTER_NAME_FAILED_PAGE } from "../../route";
//导入nanoid
import {nanoid} from "nanoid"
const store = useNoloStore();
const router = useRouter();
const route = useRoute();
let imgUrl = ref<string>();
let currentRate = ref<number>(0);
let text = ref<string>('0%');
let taskId = ref<Date>(new Date());
let processCode = ref<string>('111111');
let videoUrl = ref<string>();
onMounted(async()=>{
    
    try {
        const imgId = route.params['imgId'];
        let res =await apiGetImgUrl(imgId as string);
        imgUrl.value = res.contents[0].content;
    } catch (error) {
        console.log(`Error: ${error}`);
        
    }
    //创建任务
    const imgVideo = {
        "taskId": taskId.value.getTime().toString(),
        "meta": {
            "templateId": "1",
            "gender": "female",
            "callback": "http://ydsbfjwoxc.td/osyrtt"
        },
        "contents": [
            {
                "content": imgUrl.value,
                "type": "IMAGE"
            }
        ]
    }
    
    try {
        await apiGetImgVideo(imgVideo)
    } catch (error) {
        console.log(`error:${error}`);
        
    }
    //首次调用查询任务接口
    apiGetProcess(taskId.value.getTime().toString()).then(response=>{
        processCode.value = response.code;
    }).catch(error=>{
        console.log(`error:${error}`);
    });
    // 设置环形进度条计时器
    const TimerPoint = setInterval(()=>{
        if(currentRate.value < 99){
            let randomNum = Math.floor(Math.random() * (7-4+1)) + 4
            currentRate.value += randomNum;
            if((99 - currentRate.value) < randomNum){
                currentRate.value = 99;
            }
        }
        text.value = currentRate.value.toFixed(0) + '%';
    },700) 
    // 查询任务计时器
    const Timer = setInterval(()=>{   
        
        apiGetProcess(taskId.value.getTime().toString()).then(response=>{
            
            if(response.process === 100){
                videoUrl.value = response.contents[0].content;
                clearInterval(Timer);
                clearInterval(TimerPoint);
                currentRate.value = 100;
                text.value = currentRate.value.toFixed(0) + '%';
                //记录存入浏览器
                let videos = JSON.parse(localStorage.getItem('videos') || '[]');
                videos.push({
                    code:1,
                    videoId:nanoid(),
                    videoUrl:videoUrl.value
                });
                localStorage.setItem('videos', JSON.stringify(videos));
                router.push({
                    name:ROUTER_NAME_PREVIEW_PAGE,
                    params: {
                        videoUrl: videoUrl.value
                    }
                });
            }
            if(response.code === '100008'){
                clearInterval(Timer);
                clearInterval(Timer);
                clearInterval(TimerPoint);
                //记录存入浏览器
                let videos = JSON.parse(localStorage.getItem('videos') || '[]');
                videos.push({
                    code:0,
                    videoId:nanoid()
                });
                localStorage.setItem('videos', JSON.stringify(videos));
                router.push({
                    name:ROUTER_NAME_FAILED_PAGE,
                });
            }
        }).catch(error=>{
            console.log(`error:${error}`);
        });
    },2000);
});

const toPreviewPage = () => {
    router.push({
        name: ROUTER_NAME_PREVIEW_PAGE,
    });
};

const toGetImgUrl = () => {
    router.push({
        name:ROUTER_NAME_FAILED_PAGE
    })
};
const increaseProgress = () => {
    
    
};
</script>

<style lang="less" scoped>
@import url(../../style/index.less);
.bg {
    position: relative;
    background-color: black;
    height: 100vh;
    width: 100vw;
    padding-top: 34px;
    padding-bottom: 130px;
    text-align: center;
    color: white;
}
.box{
    top: 20px;
    width: 80%;
    height: 100vw;
    border: 1px solid white;
    text-align: center;
    margin: 40px auto 0;
}
.Loading {
    position: relative;
    top: 40%;
}
.content{
    // display: flex;
    position: relative;
    top: 30%;
}
.text {
    margin-top: 5vw;
    font-size: 3.3vw;
    color: #696969;
}
.publishBtn{
    position: fixed;
    bottom: 50px;
    left: 50%;
    transform: translateX(-50%);
    width: 150px;
    height: 10.3vw;
    background-color: #696969;
    color: ffffff;
    border: none;
    border-radius: 20px;
    font-size: 14px;
    cursor: pointer;
    
}
::v-deep .van-circle__text {
    color: #fff;
}
</style>
